package peer1

import (
	"errors"
	"reflect"
)


func ValidateNotNull(v interface{}) error {
	rt :=reflect.TypeOf(v)
	rv := reflect.ValueOf(v)
	switch rt.Kind(){
	case reflect.Invalid:
		return errors.New("类型不正确")
	case reflect.String:
		if  rv.String() == ""{
			return ERR_EMPTY_STRING
		}
	case reflect.Struct:
		for i:=0;i<rt.NumField(); i++{
			fieldT := rt.Field(i)
			fieldV := rv.Field(i)
			if  fieldT.Tag.Get("validate") == "required"{
				err :=  validateVal(fieldV)
				if err!=nil{
					return err
				}
			}
		}
	case reflect.Ptr,reflect.Interface:
		for i := 0; i < rv.Elem().Type().NumField(); i++ {
			tag := rv.Elem().Type().Field(i).Tag.Get("validate")
			if tag == "required"{
				fieldV := rv.Elem().Field(i)
				err :=  validateVal(fieldV)
				if err!=nil{
					return err
				}
			}
		}

	case reflect.Uintptr,reflect.Array, reflect.Chan, reflect.Map, reflect.Slice, reflect.UnsafePointer:

	}
	return nil
}

func validateVal(fieldV reflect.Value) error {
	switch fieldV.Kind(){
	case reflect.String:
		if fieldV.String()==""{
			return ERR_EMPTY_STRING
		}
	case reflect.Ptr:
		if fieldV.IsNil(){
			return ERR_EMPTY_ADDRESS
		}
	case reflect.Interface:
		if fieldV.IsNil(){
			return ERR_EMPTY_INTERFACE
		}
	case reflect.Slice:
		if fieldV.IsNil(){
			return ERR_EMPTY_SLICE
		}
	case reflect.Map:
		if fieldV.IsNil(){
			return ERR_EMPTY_MAP
		}
	}
	return nil
}